<template>
  <div id="app">
    <header>
      <nav>
        <router-link to="/products">商品列表</router-link>
        <router-link to="/cart">购物车</router-link>
        <router-link v-if="isAuthenticated" to="/orders">我的订单</router-link>
        <router-link v-if="isAuthenticated" to="/address">地址管理</router-link>
        <router-link v-if="isAdmin" to="/admin">管理后台</router-link>
        <button v-if="isAuthenticated" @click="logout">退出</button>
        <router-link v-else to="/login">登录</router-link>
      </nav>
    </header>

    <div class="main-container">
      <aside class="sidebar">
        <div class="category-nav">
          <h3>商品分类</h3>
          <template v-if="categoryStore.isLoading">
            <div class="loading-item">加载分类中...</div>
          </template>
          <template v-else>
            <div
                v-for="category in categories"
                :key="category.id"
                class="category-item"
                @click="toggleCategory(category.id)"
            >
              <div class="category-header">
                <span class="category-icon">{{ category.icon }}</span>
                <span class="category-name">{{ category.name }}</span>
                <span class="category-arrow">{{ expandedCategories[category.id] ? '▼' : '▶' }}</span>
              </div>

              <div
                  v-if="expandedCategories[category.id]"
                  class="category-details"
              >
                <div
                    v-for="product in getProductsByCategory(category.slug)"
                    :key="product.id"
                    class="product-item"
                >
                  <router-link
                      :to="`/products/${product.id}`"
                      class="product-link"
                      @click.native="(e) => { e.stopPropagation() }"
                  >
                    {{ product.name }} (¥{{ product.price }})
                  </router-link>
                </div>
              </div>
            </div>
          </template>
        </div>
      </aside>

      <main class="content">
        <LoadingIndicator v-if="isLoading"/>
        <NotificationContainer/>
        <router-view/>
      </main>
    </div>
  </div>
</template>

<script>
import {computed, onMounted, ref} from 'vue'
import {useAuthStore, useCategoryStore} from './store'
import {products} from './api/mockData'
import {useRouter} from 'vue-router'
import LoadingIndicator from '@/components/LoadingIndicator.vue'
import NotificationContainer from '@/components/NotificationContainer.vue'

export default {
  components: {
    LoadingIndicator,
    NotificationContainer
  },
  setup() {
    const authStore = useAuthStore()
    const router = useRouter()

    const isAuthenticated = computed(() => authStore.isAuthenticated)
    const isAdmin = computed(() => authStore.user?.isAdmin)
    const isLoading = ref(false)
    const categoryStore = useCategoryStore()

    onMounted(async () => {
      isLoading.value = true
      try {
        await categoryStore.fetchCategories()
      } finally {
        isLoading.value = false
      }
    })

    const logout = () => {
      authStore.logout()
      router.push('/login')
    }

    const categories = computed(() => categoryStore.categories)
    const expandedCategories = ref({})

    const toggleCategory = (categoryId) => {
      // 使用Vue.set确保响应式更新
      const newState = {...expandedCategories.value}
      newState[categoryId] = !newState[categoryId]
      expandedCategories.value = newState
    }

    const getProductsByCategory = (categorySlug) => {
      // 添加空值检查和缓存优化
      if (!products || !products.length) return []

      // 精确匹配分类slug，忽略大小写
      return products.filter(product =>
          product.category &&
          product.category.toLowerCase() === categorySlug.toLowerCase()
      )
    }

    // 添加窗口大小变化监听，优化移动端体验
    onMounted(() => {
      const handleResize = () => {
        if (window.innerWidth < 768) {
          // 移动端默认折叠所有分类
          const collapsedState = {}
          categories.value.forEach(cat => {
            collapsedState[cat.id] = false
          })
          expandedCategories.value = collapsedState
        }
      }

      window.addEventListener('resize', handleResize)
      handleResize() // 初始化执行

      onUnmounted(() => {
        window.removeEventListener('resize', handleResize)
      })
    })

    return {
      isAuthenticated,
      isAdmin,
      logout,
      isLoading,
      categories,
      categoryStore,
      expandedCategories,
      toggleCategory,
      getProductsByCategory
    }
  }
}
</script>

<style>
/* 使用CSS变量 */
:root {
  --primary: #4361ee;
  --primary-hover: #3f37c9;
  --text: #2c3e50;
  --bg-light: #f8f9fa;
  --border-radius: 8px;
  --transition: all 0.3s ease;
}

/* 主容器布局 */
.main-container {
  display: flex;
  min-height: calc(100vh - 80px);
}

/* 侧边栏样式 */
.sidebar {
  width: 250px;
  background: white;
  padding: 1rem;
  box-shadow: 2px 0 8px rgba(0, 0, 0, 0.1);
  border-right: 1px solid #eee;
}

/* 内容区域样式 */
.content {
  flex: 1;
  padding: 2rem;
}

/* 导航栏样式 */
header {
  position: sticky;
  top: 0;
  z-index: 100;
  background: white;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

nav {
  padding: 1rem 2rem;
  display: flex;
  align-items: center;
  gap: 1.5rem;
  max-width: 1200px;
  margin: 0 auto;
}

.category-nav h3 {
  margin: 0 0 1rem 0;
  padding-bottom: 0.5rem;
  border-bottom: 1px solid #eee;
  color: var(--text);
}

nav a {
  color: var(--text);
  text-decoration: none;
  font-weight: 500;
  padding: 0.5rem 0;
  position: relative;
  transition: var(--transition);
}

nav a:hover {
  color: var(--primary);
}

nav a.router-link-exact-active {
  color: var(--primary);
}

nav a.router-link-exact-active::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 0;
  width: 100%;
  height: 2px;
  background-color: var(--primary);
}

/* 改进按钮样式 */
nav button {
  background-color: var(--primary);
  color: white;
  border: none;
  padding: 0.5rem 1rem;
  border-radius: var(--border-radius);
  cursor: pointer;
  transition: var(--transition);
  font-weight: 500;
}

nav button:hover {
  background-color: var(--primary-hover);
  transform: translateY(-2px);
}

/* 响应式设计 */
@media (max-width: 768px) {
  nav {
    flex-direction: column;
    align-items: flex-start;
    gap: 0.5rem;
    padding: 1rem;
  }
}

/* 分类展开样式 */
.dropdown-content {
  position: absolute;
  background-color: white;
  min-width: 200px;
  box-shadow: 0 8px 16px rgba(0, 0, 0, 0.1);
  z-index: 1;
  border-radius: var(--border-radius);
  padding: 0.5rem 0;
}

.category-item {
  margin-bottom: 0;
}

.category-header {
  display: flex;
  align-items: center;
  padding: 0.5rem 1rem;
  cursor: pointer;
  transition: var(--transition);
}

category-header:hover {
  background-color: var(--bg-light);
}

.category-icon {
  margin-right: 0.5rem;
}

.category-name {
  flex-grow: 1;
}

.category-arrow {
  margin-left: 0.5rem;
  font-size: 0.8rem;
}

.category-details {
  padding: 0.5rem 0 0.5rem 1.5rem;
  background-color: var(--bg-light);
}

.product-link {
  display: block;
  padding: 0.5rem 1rem;
  color: var(--text);
  text-decoration: none;
  transition: var(--transition);
  font-size: 0.9rem;
}

.product-link:hover {
  color: var(--primary);
  background-color: rgba(67, 97, 238, 0.05);
}

.loading-item {
  padding: 0.5rem 1rem;
  color: #666;
  font-size: 0.9rem;
}
</style>
